<?php


namespace common\models\db;


class BaseModel extends \yii\db\ActiveRecord
{

    protected static $model = array();

    /**
     * @param int $page
     * @param int $pageSize
     * @param string $where
     * @param string $order
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getList($page = 1, $pageSize = 1000, $where = '', $order = 'sort desc', $asArray = true)
    {
        $condition = '1=1 ';
        if (!empty($where)) {
            $condition .= ' And ' . $where;
        }
        $query = self::find()
            ->where($condition)
            ->limit($pageSize)
            ->offset(($page - 1) * $pageSize)
            ->orderBy($order);
        if ($asArray) {
            return $query->asArray()->all();
        } else {
            return $query->all();
        }
    }

    public function getFirstErrorMsg()
    {
        $errors = array_values($this->getFirstErrors());
        return isset($errors[0]) ? $errors[0] : '保存失败';
    }

    /**
     * @param $id
     * @param $fieldNmae
     * @param string $flag
     * @return mixed|string
     */
    public static function getName($id, $fieldNmae, $flag = '')
    {
        if (!$id && $flag) {
            return '';
        }
        $key = $flag . '_' . $id;
        if (!isset(self::$model[$key])) {
            $model = self::findOne($id);
            self::$model[$key] = $model;
        }
        return self::$model[$key] ? self::$model[$key]->$fieldNmae : '';
    }
}